﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;

namespace EcoSystem
{
    /// <summary>
    /// 枚举查询接口
    /// </summary>
    public class EnumAppService : ApplicationService, IEnumAppService
    {

        /// <summary>
        /// 获取当前项目所有枚举数据
        /// </summary>
        /// <returns></returns>
        public async Task<EnumsListResultDto> GetEnumItemsAsync()
        {
            var assemble = typeof(EcoSystem.AccountType).Assembly;
            var types = assemble.GetTypes().ToList().Where(x => x.IsEnum).ToList();
            var result = new EnumsListResultDto();
            for (int i = 0; i < types.Count; i++)
            {
                var type = types[i];
                List<EnumFieldItemDto> items = new List<EnumFieldItemDto>();
                var filelds = type.GetFields();
                for (int j = 0; j < type.GetEnumValues().Length; j++)
                {
                    var field = filelds[j + 1];
                    FieldInfo fieldInfo = type.GetField(Enum.GetValues(type).GetValue(j).ToString());
                    DescriptionAttribute attr = Attribute.GetCustomAttribute(
                        fieldInfo, typeof(DescriptionAttribute), false) as DescriptionAttribute;

                    if (attr != null && !string.IsNullOrEmpty(attr.Description))
                    {
                        items.Add(new EnumFieldItemDto()
                        {
                            Name = type.GetEnumValues().GetValue(j).ToString(),
                            Description = attr.Description,
                            Value = Convert.ToInt32(Enum.GetValues(type).GetValue(j))
                        });
                    }
                    else
                    {
                        items.Add(new EnumFieldItemDto()
                        {
                            Name = type.GetEnumValues().GetValue(j).ToString(),
                            Description = type.GetEnumValues().GetValue(j).ToString(),
                            Value = Convert.ToInt32(Enum.GetValues(type).GetValue(j))
                        });
                    }
                }

                if (items.Count > 0)
                {
                    DescriptionAttribute enumAttr = Attribute.GetCustomAttribute(type,
                        typeof(DescriptionAttribute), false) as DescriptionAttribute;
                    var description = enumAttr?.Description ?? type.Name;
                    result.Add(type.Name, new EnumItemDto
                    {
                        Name = type.Name,
                        Description = description,
                        Items = items
                    });
                }
            }
            return await Task.FromResult(result);
        }
    }
}